package com.keur.money.ui.main.impl

import android.content.Context
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.BaseFragment
import com.keur.money.http.ApiService
import com.keur.money.http.ApiService.addCommonParams
import com.keur.money.http.ApiService.addRandomParams
import com.keur.money.http.HttpHelper
import com.keur.money.http.IHttpCallback
import com.keur.money.mvp.presenter.MvpPresenter
import com.keur.money.ui.main.fm.KeurCouponFm
import com.keur.money.ui.main.fm.KeurHomeFm
import com.keur.money.ui.main.fm.KeurRepayFm
import com.keur.money.ui.main.fm.KeurUserFm
import com.keur.money.ui.main.view.IKeurMainView
import com.keur.money.utils.DateUtils
import com.keur.money.utils.event.KeurEventData
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.KeurSignRiseHelper
import com.keur.money.utils.helper.KeurUserCouponHelper
import com.keur.money.utils.helper.KeurUserPointsHelper
import com.keur.money.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 15:46
 * @Annotation：主页面 Presenter 实现
 */
class KeurMainPresenterImpl(context: Context?) : MvpPresenter<IKeurMainView>(context) {
    //val 是不可变的 var 可变的
    private val tabImageNormal = arrayListOf(
        R.mipmap.mulla_tab_home_normal,
        R.mipmap.mulla_tab_repayment_normal,
        R.mipmap.mulla_tab_coupon_normal,
        R.mipmap.mulla_tab_user_normal
    )

    private val tabImageSelect = arrayListOf(
        R.mipmap.mulla_tab_home_selected,
        R.mipmap.mulla_tab_repayment_selected,
        R.mipmap.mulla_tab_coupon_selected,
        R.mipmap.mulla_tab_user_selected
    )

    //定义tab的每个页面
    private val tabList = arrayListOf<JSONObject>()
    private val fragments = ArrayList<BaseFragment>()
    private var curtIndex = 0

    /**
     * 加载Tabbar数据
     */
    fun loadMullaTabList(){
        tabList.clear()
        //tab
        for (i in 0 until tabImageNormal.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("tabImageSelected", tabImageSelect[i])
            tabObj.put("tabImageNormal", tabImageNormal[i])
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        mvpView?.showMullaTabList(tabList)
    }

    /**
     * 加载FragmentList
     */
    fun loadMullaFragmentList(){
        fragments.add(KeurHomeFm())//首页
        fragments.add(KeurRepayFm())//还款
        fragments.add(KeurCouponFm())//优惠券
        fragments.add(KeurUserFm())//个人中心

        mvpView?.showMullaLoading()
        //获取产品列表，判断是否有待还款产品
        loadMullaProductListAction(true)
    }

    /**
     * 切换Tab
     */
    fun setMullaCurrentItemIndex(index: Int) {
        curtIndex = index
        if (curtIndex < 0){
            curtIndex = 0
        }
        for (tabObj in tabList) {
            when (tabObj.optInt("tabId")) {
                curtIndex -> {
                    tabObj.put("isSelect", true)
                }
                else -> {
                    tabObj.put("isSelect", false)
                }
            }
        }
        mvpView?.notifyTabDataChanged()

        val fragment = fragments[curtIndex]
        mvpView?.showMullaFragment(fragment,curtIndex)

        //切换Tab需要刷新签到信息 获取积分
        loadMullaUserSignInfoAction()
        //获取优惠券信息
        KeurUserCouponHelper.loadMullaUserCouponListAction()
    }

    /**
     * 获取总流程
     */
    fun loadMullaProcessAction() {
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_PROCESS_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
//            put("path", ApiService.API_PATH.MULLA_API_PROCESS_PATH)
        }
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code",0)) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        //保存用户流程状态
                        if (obj != null) {
                            // TODO: 测试添加 Step 类型
//                            val allStepTitles = obj.optJSONArray("allStepTitles")
//                            allStepTitles.put("Ocr Info")
//                            allStepTitles.put("Face recognition")
//                            allStepTitles.put("Account Info")
//                            val allSteps = obj.optJSONArray("allSteps")
//                            allSteps.put("ocr_info")
//                            allSteps.put("sefie_info")
//                            allSteps.put("account_info")
//                            val steps = obj.optJSONArray("steps")
//                            steps.put("ocr_info")
//                            val index = Random.nextInt(3)
//                            when(index){
//                                0 -> {
//                                    steps.put("ocr_info")
//                                }
//                                1 -> {
//                                    steps.put("sefie_info")
//                                }
//                                else -> {
//                                    steps.put("account_info")
//                                }
//                            }
                            SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_PROCESS, obj.toString())
                            //通知全局流程刷新完成
                            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PROCESS_REFRESHED))

                            // TODO: 根据 smsFlag 或 whatsappFlag 判断是否需要校验手机号
                            val smsFlag = obj.optString("smsFlag") == "YES"
                            val whatsappFlag = obj.optString("whatsappFlag") == "YES"
                            if (smsFlag or whatsappFlag){//需要校验手机号
                                mvpView?.ShowMullaVerificationPage()
                            }
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取签到信息
     * signType:
     *          getSignInfo - 查询用户签到信息
     *          userSignIn - 保存用户签到信息
     */
    fun loadMullaUserSignInfoAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_SIGN_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("mobile", SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_MOBILE))
            put("signType","getSignInfo")
        }
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            obj.put("lastSignTime",obj.optString("lastSignTime").replace("-",""))
                            //保存用户签到信息
                            SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_SIGN_INFO,obj.toString())
                            //刷新积分完成
                            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_POINTS_REFRESHED))

                            //上次签到时间
                            val lastSignTime = obj.optString("lastSignTime")
                            //连续签到天数
                            val conSignTime = obj.optString("conSignTime")

                            //没有签到时间 - 没有签过到
                            if (lastSignTime.isEmpty() || "0" == lastSignTime){
                                saveMullaUserSignAction("1")
                            } else {
                                //签过到
                                //上次签到时间是否是今天
                                if (DateUtils.IsToday(lastSignTime.toLong() * 1000)){
                                    //签过到了
                                    /**
                                     * TODO: 2025/05/26-2025/05/30 赞比亚更新新需求，增加签到提额逻辑
                                     */
                                    KeurSignRiseHelper.onMullaHandleSignRiseData(mvpView?.getContext())
                                } else {
                                    //上次签到时间是否是昨天
                                    if (DateUtils.IsYesterday(lastSignTime.toLong() * 1000)){
                                        //连续签到天数 +1
                                        saveMullaUserSignAction("${conSignTime.toInt() + 1}")
                                    } else {
                                        //非连续签到： 连续签到天数 1
                                        saveMullaUserSignAction("1")
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 签到
     */
    fun saveMullaUserSignAction(conSignTime: String){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_SIGN_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("mobile", SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_MOBILE))
            put("signType","userSignIn")
            put("signDate", System.currentTimeMillis() / 1000)//签到时间戳
            put("conSignTime", conSignTime)//连续签到天数
        }
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            // 连续签到增加积分数
                            val signPoints = KeurCustomConfigsHelper.getMullaSignPointsBySignTime(conSignTime.toInt())
                            //弹窗签到成功dialog
                            mvpView?.showMullaSignSuccessDialog(signPoints)
                            //签到成功 存储签到积分
                            KeurUserPointsHelper.saveMullsUserPointsAction("signPoints",MyApp.app.getString(R.string.points_use_info_check_in),signPoints)
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取产品列表
     * 存在待还款的产品 ，需要直接展示Repay，否则显示可申请产品列表
     */
    fun loadMullaProductListAction(isCheck: Boolean = false){
        val params = JSONObject()
            .addCommonParams()
            .addRandomParams()
            .apply {
                put("mobile", SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_MOBILE))
                put("env", "dev")
                put("showDailyIncrease",true)
            }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_PRODUCT_LIST_PATH)
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                var showTabIndex = 0
                when(data.optInt("code")) {
                    0 -> {//成功
                        SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_PRODCTS,data.optString("obj"))
                        MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PRODUCT_REFRESHED))

                        val objArray = data.optJSONArray("obj")
                        if (objArray != null) {
                            //可申请的产品数量
                            var productCount = 0
                            for (i in 0..<objArray.length()){
                                val item = objArray.optJSONObject(i)
                                //可申请的产品
                                if (item.optString("activeFlag") == "YES"){
                                    productCount++
                                }

                                //待还款的产品
                                if ("REPAYMENT" == item.optString("status")){
                                    showTabIndex = 1
                                }
                            }
                            //保存用户VIP等级
                            saveMullaUserVip(productCount)
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
                if (isCheck){
                    //默认选中第1个
                    setMullaCurrentItemIndex(showTabIndex)
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_PRODUCT_FINISHED))
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 保存用户Vip等级
     */
    fun saveMullaUserVip(pCount: Int){
        if (pCount <= 1){
            SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_VIP,1)
        } else if (pCount > 4){
            SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_VIP,3)
        } else {
            SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_VIP,2)
        }
    }
}